package com.example.logindemo.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/external")
public class ExternalApiController {

    private final RestTemplate restTemplate = new RestTemplate();

    // 获取天气信息
    @GetMapping("/weather")
    public ResponseEntity<?> getWeather(@RequestParam String city) {
        try {
            // 为不同城市设置不同的天气数据，更接近真实API行为
            Map<String, Object> weatherData = new HashMap<>();
            weatherData.put("city", city);
            
            // 为不同城市设置不同的天气和温度
            Map<String, String> cityWeather = new HashMap<>();
            cityWeather.put("北京", "晴");
            cityWeather.put("上海", "多云");
            cityWeather.put("广州", "阵雨");
            cityWeather.put("深圳", "阴");
            cityWeather.put("杭州", "小雨");
            cityWeather.put("成都", "雾");
            cityWeather.put("重庆", "多云转晴");
            cityWeather.put("武汉", "晴转多云");
            cityWeather.put("西安", "晴");
            cityWeather.put("南京", "阴转多云");
            
            // 基础温度，根据城市有所不同
            Map<String, Integer> baseTemp = new HashMap<>();
            baseTemp.put("北京", 28);
            baseTemp.put("上海", 26);
            baseTemp.put("广州", 30);
            baseTemp.put("深圳", 29);
            baseTemp.put("杭州", 27);
            baseTemp.put("成都", 25);
            baseTemp.put("重庆", 32);
            baseTemp.put("武汉", 31);
            baseTemp.put("西安", 29);
            baseTemp.put("南京", 27);
            
            // 获取城市特定数据或使用默认值
            String weather = cityWeather.getOrDefault(city, "晴转多云");
            int temp = baseTemp.getOrDefault(city, 25);
            
            // 添加一些随机变化，模拟实时更新
            int variation = (int)(Math.random() * 4) - 2; // -2 到 +2 的随机变化
            
            // 设置天气数据
            weatherData.put("weather", weather);
            weatherData.put("weatherIcon", getWeatherIcon(weather));
            weatherData.put("temperature", temp + variation);
            weatherData.put("feelsLike", temp + variation + (weather.contains("雨") ? 0 : 2));
            weatherData.put("humidity", 40 + (int)(Math.random() * 30) + (weather.contains("雨") ? 15 : 0));
            weatherData.put("windSpeed", String.format("%.1f", 2 + Math.random() * 5));
            weatherData.put("pressure", 1010 + (int)(Math.random() * 10));
            weatherData.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            weatherData.put("updateTime", new SimpleDateFormat("HH:mm:ss").format(new Date()));
            
            return ResponseEntity.ok(weatherData);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "获取天气信息失败"));
        }
    }
    
    // 根据天气类型获取对应的图标
    private String getWeatherIcon(String weather) {
        if (weather.contains("晴")) return "☀️";
        if (weather.contains("云")) return "⛅";
        if (weather.contains("阴")) return "☁️";
        if (weather.contains("雨")) return "🌦️";
        if (weather.contains("雾")) return "🌫️";
        return "☀️";
    }

    // 获取汇率信息
    @GetMapping("/exchange")
    public ResponseEntity<?> getExchangeRates() {
        try {
            // 基础汇率数据
            Map<String, Double> baseRates = new HashMap<>();
            baseRates.put("USD", 0.1428);
            baseRates.put("EUR", 0.1315);
            baseRates.put("JPY", 21.45);
            baseRates.put("GBP", 0.1123);
            baseRates.put("HKD", 1.1234);
            baseRates.put("KRW", 189.56);
            baseRates.put("SGD", 0.1921);
            baseRates.put("AUD", 0.2156);
            
            Map<String, String> currencyNames = new HashMap<>();
            currencyNames.put("USD", "美元");
            currencyNames.put("EUR", "欧元");
            currencyNames.put("JPY", "日元");
            currencyNames.put("GBP", "英镑");
            currencyNames.put("HKD", "港币");
            currencyNames.put("KRW", "韩元");
            currencyNames.put("SGD", "新加坡元");
            currencyNames.put("AUD", "澳元");
            
            List<Map<String, String>> rates = new ArrayList<>();
            
            // 为每种货币添加基于时间的微小变化，模拟市场波动
            Calendar cal = Calendar.getInstance();
            int minuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
            
            for (Map.Entry<String, Double> entry : baseRates.entrySet()) {
                String code = entry.getKey();
                double baseRate = entry.getValue();
                
                // 添加基于时间的微小变化，模拟市场波动
                double variation = (minuteOfDay % 5 - 2) * 0.0001 * (code.equals("JPY") ? 10 : 1);
                double newRate = baseRate + variation;
                
                // 计算涨跌幅
                String changeSign = variation >= 0 ? "↑" : "↓";
                double changePercent = Math.abs((variation / baseRate) * 100);
                String change = changeSign + String.format("%.2f%%", changePercent);
                
                // 格式化汇率值，根据货币不同设置不同的小数位
                String rateFormat = code.equals("JPY") || code.equals("KRW") ? "%.2f" : "%.4f";
                String rateValue = String.format(rateFormat, newRate);
                
                Map<String, String> rateMap = new HashMap<>();
                rateMap.put("currency", currencyNames.get(code));
                rateMap.put("code", code);
                rateMap.put("rate", rateValue);
                rateMap.put("change", change);
                rates.add(rateMap);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("base", "CNY");
            response.put("rates", rates);
            response.put("updateTime", new SimpleDateFormat("HH:mm:ss").format(new Date()));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "获取汇率信息失败"));
        }
    }

    // 获取新闻信息
    @GetMapping("/news")
    public ResponseEntity<?> getNews(@RequestParam(defaultValue = "general") String category) {
        try {
            // 使用NewsAPI获取新闻数据
            // 这里使用模拟数据结构，但按照不同分类返回不同内容
            List<Map<String, String>> articles = getNewsByCategory(category);
            
            Map<String, Object> response = new HashMap<>();
            response.put("category", category);
            response.put("articles", articles);
            response.put("updateTime", new SimpleDateFormat("HH:mm:ss").format(new Date()));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "获取新闻信息失败"));
        }
    }

    private List<Map<String, String>> getNewsByCategory(String category) {
        List<Map<String, String>> articles = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // 不同类别的新闻标题
        Map<String, List<String[]>> categoryNews = new HashMap<>();
        
        // 商业新闻
        categoryNews.put("business", Arrays.asList(
            new String[]{"央行：继续实施稳健的货币政策，保持流动性合理充裕", "金融时报", "https://finance.sina.com.cn"},
            new String[]{"国内消费市场持续回暖，上半年消费增速超预期", "经济观察报", "https://www.eeo.com.cn"},
            new String[]{"多家银行下调存款利率，引导资金流向实体经济", "财经网", "https://finance.qq.com"},
            new String[]{"A股市场震荡上行，科技板块表现活跃", "证券时报", "https://www.stcn.com"},
            new String[]{"新能源汽车产业链迎来投资热潮", "第一财经", "https://www.yicai.com"}
        ));
        
        // 科技新闻
        categoryNews.put("technology", Arrays.asList(
            new String[]{"我国量子计算研究取得重大突破，实现76个光子量子优势", "科技日报", "https://www.stdaily.com"},
            new String[]{"AI大模型应用落地加速，多个行业迎来智能化转型", "中国科学报", "https://news.sciencenet.cn"},
            new String[]{"5G-A网络试点启动，传输速度提升10倍", "通信世界", "https://www.cww.net.cn"},
            new String[]{"国产操作系统市场份额持续提升", "IT之家", "https://www.ithome.com"},
            new String[]{"元宇宙技术应用场景不断拓展", "36氪", "https://36kr.com"}
        ));
        
        // 体育新闻
        categoryNews.put("sports", Arrays.asList(
            new String[]{"中国女排3-0横扫日本队，夺得世界女排联赛冠军", "中国体育报", "https://sports.sina.com.cn"},
            new String[]{"CBA总决赛第三场：广东队险胜辽宁队，总比分2-1", "篮球先锋报", "https://sports.sohu.com"},
            new String[]{"中超联赛第十轮战报：上海海港2-0胜北京国安", "足球周刊", "https://sports.163.com"},
            new String[]{"中国选手在世界田径锦标赛上再获两枚金牌", "体坛周报", "https://www.titan24.com"},
            new String[]{"游泳世锦赛：中国队首日斩获两金一银", "游泳世界", "https://swimworld.com.cn"}
        ));
        
        // 健康新闻
        categoryNews.put("health", Arrays.asList(
            new String[]{"最新研究：每天步行8000步可显著降低慢性疾病风险", "健康时报", "https://health.sina.com.cn"},
            new String[]{"国家医保局：新版医保目录7月1日起正式实施", "中国医疗保险", "https://www.zgylbx.com"},
            new String[]{"夏季高温来袭，专家提醒注意防暑降温", "医学论坛网", "https://www.medtrib.cn"},
            new String[]{"青少年心理健康问题引发关注，多部门联合出台解决方案", "健康中国", "https://www.health-china.com"},
            new String[]{"重大疾病防治取得新进展，创新药物临床效果显著", "中国医学论坛报", "https://www.cmt.com.cn"}
        ));
        
        // 教育新闻
        categoryNews.put("education", Arrays.asList(
            new String[]{"教育部：推进高校\"双一流\"建设，提升高等教育质量", "中国教育报", "https://www.jyb.cn"},
            new String[]{"新一轮高考改革方案公布，更加注重学生全面发展", "中国青年报", "https://zqb.cyol.com"},
            new String[]{"职业教育改革深化，产教融合成为发展重点", "职教论坛", "https://zjol.com.cn"},
            new String[]{"在线教育行业规范发展，质量提升成为核心竞争力", "教育信息化", "https://www.edu.cn"},
            new String[]{"国际教育交流重启，留学市场逐步回暖", "留学杂志", "https://www.liuxue.com"}
        ));
        
        // 旅游新闻
        categoryNews.put("travel", Arrays.asList(
            new String[]{"文化和旅游部推出暑期文化旅游消费季活动", "中国旅游报", "https://www.ctnews.com.cn"},
            new String[]{"国内旅游市场全面复苏，热门景区客流攀升", "旅游周刊", "https://travel.sohu.com"},
            new String[]{"多个省份发放文旅消费券，刺激旅游市场活力", "环球旅游", "https://travel.sina.com.cn"},
            new String[]{"乡村旅游成为新热点，带动乡村振兴发展", "中国乡村振兴", "https://www.zgxczx.gov.cn"},
            new String[]{"出境游市场有序恢复，首批国际航线复航", "民航资源网", "https://www.carnoc.com"}
        ));
        
        // 默认新闻
        List<String[]> defaultNews = Arrays.asList(
            new String[]{"国家发改委：将加强基础设施建设，推动经济高质量发展", "央视新闻", "https://news.cctv.com"},
            new String[]{"我国新能源汽车出口量持续增长，创历史新高", "新华社", "https://www.xinhuanet.com"},
            new String[]{"国务院发布最新政策，支持中小企业发展", "人民日报", "https://www.people.com.cn"},
            new String[]{"全国多地迎来强降雨，防汛工作全面展开", "中国天气网", "https://www.weather.com.cn"},
            new String[]{"科技创新成为经济发展新引擎，研发投入持续增加", "光明日报", "https://www.gmw.cn"}
        );
        
        // 获取对应类别的新闻或使用默认新闻
        List<String[]> newsItems = categoryNews.getOrDefault(category, defaultNews);
        
        // 生成新闻数据，时间随机分布在最近24小时内
        for (int i = 0; i < Math.min(newsItems.size(), 5); i++) { // 最多显示5条新闻
            String[] item = newsItems.get(i);
            
            // 随机设置发布时间，在过去24小时内
            int hoursAgo = (int)(Math.random() * 24);
            int minutesAgo = (int)(Math.random() * 60);
            Calendar publishCal = (Calendar)cal.clone();
            publishCal.add(Calendar.HOUR_OF_DAY, -hoursAgo);
            publishCal.add(Calendar.MINUTE, -minutesAgo);
            
            Map<String, String> article = new HashMap<>();
            article.put("title", item[0]);
            article.put("source", item[1]);
            article.put("publishTime", dateFormat.format(publishCal.getTime()));
            article.put("url", item[2]);
            articles.add(article);
        }
        
        // 按发布时间排序（最新的在前）
        articles.sort((a, b) -> b.get("publishTime").compareTo(a.get("publishTime")));
        
        return articles;
    }
}